package com.treasure.mall.zbqmallmanager.controller.product;

import com.alibaba.fastjson.JSON;
import com.treasure.mall.biz.base.UserDetails;
import com.treasure.mall.biz.dto.condition.ProductApiSearchCondition;
import com.treasure.mall.biz.dto.condition.ProductSearchCondition;
import com.treasure.mall.biz.dto.product.LiveProductSaveDTO;
import com.treasure.mall.biz.dto.product.NormalProductSaveDTO;
import com.treasure.mall.biz.entity.product.CategoryPO;
import com.treasure.mall.biz.entity.product.ProductImgPO;
import com.treasure.mall.biz.entity.product.ProductPO;
import com.treasure.mall.biz.entity.user.MerchantPO;
import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.service.core.product.ProductImgService;
import com.treasure.mall.biz.service.core.product.ProductService;
import com.treasure.mall.biz.service.core.product.SpecialAreaService;
import com.treasure.mall.biz.service.core.user.MerchantService;
import com.treasure.mall.biz.service.core.user.UserService;
import com.treasure.mall.zbq.common.StringUtilsExt;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbq.common.base.ResultCodeEnum;
import com.treasure.mall.zbq.common.constant.Constant;
import com.treasure.mall.zbq.common.exception.ApiException;
import com.treasure.mall.zbq.common.ienum.auth.RoleEnum;
import com.treasure.mall.zbq.common.ienum.base.CodeDescEnumHelper;
import com.treasure.mall.zbq.common.ienum.product.ProductEnums;
import com.treasure.mall.zbqmallmanager.vo.FindUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wm
 */
@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductImgService productImgService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private UserService userService;
    @Autowired
    private SpecialAreaService specialAreaService;

    // region 普通产品
    @GetMapping("/normalList")
    @SuppressWarnings("Duplicates")
    public String normalList(
            @AuthenticationPrincipal UserDetails userDetails,
            @ModelAttribute("condition") ProductSearchCondition condition,
            @RequestParam(required = false, defaultValue = "1") int pageIndex,
            Model model
    ) {
        condition.setProductType(ProductEnums.ProductType.NORMAL.getCode());
        Page<ProductPO> productPOS = productService.findAll(pageIndex, Constant.DEFAULT_PAGE_SIZE, condition);
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", productPOS.getTotalElements());
        model.addAttribute("totalPages", productPOS.getTotalPages());
        model.addAttribute("productList", productPOS.getContent());
        model.addAttribute("areas", specialAreaService.findAreaAll());
        return "product/normal-list";
    }

    @GetMapping("/normalEdit")
    public String normalEdit(
            @AuthenticationPrincipal UserDetails userDetails,
            int saleType,
            Long productId,
            Model model
    ) {
        Long merchantId = 0L;
        if (userDetails.getRoleType().equals(RoleEnum.MERCHANT)) {
            merchantId = userDetails.getId();
        }
        ProductPO productInfo;
        List<ProductImgPO> imgPOList;
        CategoryPO categoryPO;
        String catTreePath = "";
        if (productId > 0) {
            //编辑模式下，类目信息读取商品上的
            productInfo = productService.findById(productId);
            imgPOList = productImgService.getImgList(productId);
            categoryPO = productInfo.getCategory();
            merchantId = productInfo.getMerchantPO().getMerchantId();

        } else {
            if (merchantId == 0) {
                throw new ApiException(ApiResult.errorWith(ResultCodeEnum.ERROR, "非商家账号不能添加产品"));
            }
            //添加模式从商家所属类目上取
            categoryPO = merchantService.findById(merchantId).getData().getMainCategory();
            productInfo = new ProductPO();
            productInfo.setLimitedNum(0);
            imgPOList = new ArrayList<>();
        }
        if (categoryPO != null) {
            catTreePath = categoryPO.getTreePath();
        }
        MerchantPO merchantPO = merchantService.findById(merchantId);
        model.addAttribute("productTags", ProductEnums.ProductTag.values());
        model.addAttribute("serviceTags", ProductEnums.ServiceTag.values());
        model.addAttribute("productInfo", productInfo);
        model.addAttribute("productImages", imgPOList);
        model.addAttribute("merchantId", merchantId);
        model.addAttribute("commissionRate", merchantPO.getCommissionRate() == null ? -1 : merchantPO.getCommissionRate());
        List<String> picList = new ArrayList<>();
        imgPOList.forEach(x -> picList.add(x.getBig()));
        model.addAttribute("picList", JSON.toJSONString(picList));
        model.addAttribute("catTreePath", StringUtilsExt.trim(catTreePath, '|'));
        model.addAttribute("isMerchant", userDetails.getRoleType().equals(RoleEnum.MERCHANT));
        model.addAttribute("saleType", CodeDescEnumHelper.getEnumTypeByCode(ProductEnums.SaleType.class, saleType));
        return "product/normal-edit";
    }

    @PostMapping("/normalSave")
    @ResponseBody
    public ApiResult normalSave(NormalProductSaveDTO saveDTO, int saleTypeCode) {
        saveDTO.setProductType(ProductEnums.ProductType.NORMAL.getCode());
        saveDTO.setSaleType(CodeDescEnumHelper.getEnumTypeByCode(ProductEnums.SaleType.class, saleTypeCode));
        ApiResult result = productService.saveNormalProduct(saveDTO);
        if (result.isSuccess()) {
            return ApiResult.ok();
        }
        return ApiResult.error(result.getResultMsg());
    }

    @PostMapping("/normalDel")
    @ResponseBody
    public ApiResult normalDel(Long productId) {
        return productService.delProduct(productId);
    }

    @GetMapping("testApiSearch")
    @ResponseBody
    public ApiResult testApiSearch() {
        ProductApiSearchCondition condition = new ProductApiSearchCondition();
        condition.setRecommendFlag(1);
        Object obj = productService.search(condition);
        return ApiResult.resultWith(ResultCodeEnum.SUCCESS, obj);
    }

    @GetMapping("testApiGetDetail")
    @ResponseBody
    public ApiResult testApiGetDetail() {
        Object obj = productService.getDetail(1L);
        return ApiResult.resultWith(ResultCodeEnum.SUCCESS, obj);
    }

    //endregion

    // region 直播产品
    @GetMapping("/liveList")
    @SuppressWarnings("Duplicates")
    public String liveList(
            @AuthenticationPrincipal UserDetails userDetails,
            @ModelAttribute("condition") ProductSearchCondition condition,
            @RequestParam(required = false, defaultValue = "1") int pageIndex,
            Model model
    ) {
        condition.setProductType(ProductEnums.ProductType.LIVE_BROADCAST.getCode());
        Page<ProductPO> productPOS = productService.findAll(pageIndex, Constant.DEFAULT_PAGE_SIZE, condition);
        productService.processExclusiveUser(productPOS.getContent());
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", productPOS.getTotalElements());
        model.addAttribute("totalPages", productPOS.getTotalPages());
        model.addAttribute("productList", productPOS.getContent());
        return "product/live-list";
    }

    @GetMapping("/liveEdit")
    public String liveEdit(
            @AuthenticationPrincipal UserDetails userDetails,
            Long productId,
            Model model
    ) {
        ProductPO productInfo;
        if (productId > 0) {
            productInfo = productService.findById(productId);
        } else {
            productInfo = new ProductPO();
        }
        model.addAttribute("serviceTags", ProductEnums.ServiceTag.values());
        model.addAttribute("productInfo", productInfo);
        return "product/live-edit";
    }

    @GetMapping("/liveSimpleEdit")
    public String liveSimpleEdit(
            @AuthenticationPrincipal UserDetails userDetails,
            Long productId,
            @RequestParam(required = false, defaultValue = "0") long roomId,
            Model model
    ) {
        Long merchantId = 0L;
        if (userDetails.getRoleType().equals(RoleEnum.MERCHANT)) {
            merchantId = userDetails.getId();
        }
        ProductPO productInfo;
        if (productId > 0) {
            productInfo = productService.findById(productId);
        } else {
            if (merchantId == 0) {
                throw new ApiException(ApiResult.errorWith(ResultCodeEnum.ERROR, "非商家账号不能添加产品"));
            }
            productInfo = new ProductPO();
        }
        model.addAttribute("serviceTags", ProductEnums.ServiceTag.values());
        model.addAttribute("productInfo", productInfo);
        model.addAttribute("roomId", roomId);
        model.addAttribute("merchantId", merchantId);
        List<String> picList = new ArrayList<>();
        picList.add(productInfo.getMainPic());
        model.addAttribute("picList", JSON.toJSONString(picList));
        UserPO user = null;
        if (productInfo.getExclusiveUserId() != null && productInfo.getExclusiveUserId() > 0) {
            user = userService.findById(productInfo.getExclusiveUserId());
        }
        if (user == null) {
            user = new UserPO();
            user.setUserId(0L);
            user.setMobile("");
            user.setNickName("");
        }
        model.addAttribute("exclusiveUser", new FindUserVO(user));
        return "product/live-simple-edit";
    }

    @PostMapping("/liveSave")
    @ResponseBody
    public ApiResult liveSave(LiveProductSaveDTO saveDTO, int saleTypeCode) {
        saveDTO.setSaleType(CodeDescEnumHelper.getEnumTypeByCode(ProductEnums.SaleType.class, saleTypeCode));
        ApiResult result = productService.saveLiveProduct(saveDTO);
        if (result.isSuccess()) {
            return ApiResult.ok();
        }
        return ApiResult.error(result.getResultMsg());
    }

    @PostMapping("/liveDel")
    @ResponseBody
    public ApiResult liveDel(Long productId) {
        return productService.delProduct(productId);
    }

    @PostMapping("/changeStatus")
    @ResponseBody
    public ApiResult changeStatus(Long productId, Integer status) {
        return productService.changeStatus(productId, status);
    }

    //endregion
}